package com.delos.rest.aspect;

import com.delos.api.error.ExceptionEnum;
import com.delos.api.exception.ServiceException;
import com.delos.rest.response.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author zouyaowen
 * @date 2020-05-15
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
    /**
     * 异常拦截
     *
     * @param e 异常对象
     * @return 统一处理异常后的返回值
     */
    @SuppressWarnings("all")
    @ExceptionHandler({Exception.class})
    @ResponseBody
    public CommonResponse<Object> serviceExceptionHandler(Exception e) {
        CommonResponse res = new CommonResponse();
        if (e instanceof ServiceException) {
            ServiceException se = (ServiceException) e;
            res.setCode(se.getErrorCode());
            res.setMessage(se.getMessage());
            return res;
        }
        /**
         * 参数异常处理
         */
        if (e instanceof ConstraintViolationException) {
            log.error("参数异常", e);
            ConstraintViolationException cve = (ConstraintViolationException) e;
            res.setCode(ExceptionEnum.PARAM_ERROR.getCode());
            String message = cve.getMessage();
            res.setMessage(message.substring(message.indexOf(" ") + 1, message.length()));
            return res;
        }
        log.error("服务器内部异常", e);
        //处理其他异常……
        res.setCode(ExceptionEnum.INTERNAL_ERROR.getCode());
        res.setMessage(ExceptionEnum.INTERNAL_ERROR.getMessage());
        return res;
    }
}
